﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;

namespace Sapphire.Linq.Framework
{
    public class SPMetadataCache
    {
        private readonly List<KeyValuePair<Type, SPList>> _lists = new List<KeyValuePair<Type, SPList>>();

        public void AddList(Type type, SPList list)
        {
            _lists.Add(new KeyValuePair<Type, SPList>(type, list));
        }

        public bool ContainsList(Type type, string listUrl)
        {
            return ContainsList(type, l => listUrl == l.RootFolder.Url);
        }

        public bool ContainsList(Type type, Guid listId)
        {
            return ContainsList(type, l => l.ID == listId);
        }

        private bool ContainsList(Type type, Func<SPList, bool> spec)
        {
            var keyValuePairs = _lists
                .Where(l => l.Key == type);

            var lists = keyValuePairs
                .Select(l => l.Value).ToList();

            return lists.FirstOrDefault(spec) != null;
        }

        public SPList GetList(Type type, string listUrl)
        {
            return GetList(type, l => listUrl == l.RootFolder.Url);
        }

        public SPList GetList(Type type, Guid listId)
        {
            return GetList(type, l => l.ID == listId);
        }

        private SPList GetList(Type type, Func<SPList, bool> spec)
        {
            return _lists
               .Where(l => l.Key == type)
               .Select(l => l.Value)
               .First(spec);
        }
    }
}